<template>
  <div class="index-container">
    <el-container>
      <el-header class="header">
        <div class="header-content">
          <h1>校园二手交易平台</h1>
          <div class="user-info">
            <el-avatar :src="userInfo.avatar" @click="goToProfile" class="user-avatar" />
            <span>欢迎，{{ userInfo.nickName || '用户' }}</span>
            <el-button type="primary" @click="logout">退出登录</el-button>
          </div>
        </div>
      </el-header>
      
      <el-main class="main-content">
        <!-- 分类标签 -->
        <div class="category-tabs">
          <el-radio-group v-model="currentLabel" @change="handleLabelChange">
            <el-radio-button :value="0">全部</el-radio-button>
            <el-radio-button :value="1">数码科技</el-radio-button>
            <el-radio-button :value="2">生活用品</el-radio-button>
            <el-radio-button :value="3">运动相关</el-radio-button>
            <el-radio-button :value="4">图书笔记</el-radio-button>
          </el-radio-group>
        </div>

        <!-- 商品列表 -->
        <div class="goods-list" v-loading="loading">
          <el-empty v-if="goodsList.length === 0" description="暂无商品" />
          <el-row :gutter="20" v-else>
            <el-col :span="6" v-for="item in goodsList" :key="item.id">
              <el-card class="goods-card" shadow="hover">
                <div class="goods-image">
                  <img :src="getFirstImage(item.pictureList)" alt="商品图片" />
                </div>
                <div class="goods-info">
                  <h3 class="goods-name">{{ item.idleName }}</h3>
                  <p class="goods-price">¥{{ item.idlePrice }}</p>
                  <div class="goods-desc-wrapper">
                    <p class="goods-desc">{{ item.idleDetails || '暂无描述' }}</p>
                    <el-button 
                      v-if="item.idleDetails && item.idleDetails.length > 50" 
                      type="text" 
                      size="small" 
                      @click="showFullDesc(item)">
                      查看全部
                    </el-button>
                  </div>
                  <div class="goods-bottom">
                    <p class="goods-place">
                      <el-icon><Location /></el-icon>
                      {{ item.idlePlace }}
                    </p>
                    <el-button type="primary" size="small" @click="buyItem(item)">购买</el-button>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :total="total"
            layout="total, prev, pager, next"
            @current-change="handlePageChange"
          />
        </div>
      </el-main>
    </el-container>

    <!-- 商品描述弹窗 -->
    <el-dialog v-model="descDialogVisible" title="商品描述" width="500px">
      <p style="line-height: 1.8; white-space: pre-wrap;">{{ currentDesc }}</p>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Location } from '@element-plus/icons-vue'
import api from '../api'

const router = useRouter()
const userInfo = ref({})
const currentLabel = ref(0)
const goodsList = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(8)
const total = ref(0)
const descDialogVisible = ref(false)  // 弹窗显示状态
const currentDesc = ref('')  // 当前查看的描述

onMounted(() => {
  const storedUserInfo = sessionStorage.getItem('userInfo')
  if (storedUserInfo) {
    userInfo.value = JSON.parse(storedUserInfo)
  }
  loadGoodsList()
})

const logout = () => {
  sessionStorage.removeItem('userInfo')
  ElMessage.success('退出成功')
  router.push('/login')
}

// 跳转到个人中心
const goToProfile = () => {
  router.push('/profile')
}

// 加载商品列表
const loadGoodsList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      nums: pageSize.value,
      findValue: ''
    }
    
    let res
    if (currentLabel.value === 0) {
      // 查询全部商品
      res = await api.getIdleItemList(params)
    } else {
      // 按分类查询
      params.idleLabel = currentLabel.value
      res = await api.getIdleItemByLabel(params)
    }
    
    if (res.status_code === 1) {
      goodsList.value = res.data.records || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.msg || '获取商品列表失败')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('网络错误')
  } finally {
    loading.value = false
  }
}

// 分类切换
const handleLabelChange = () => {
  currentPage.value = 1
  loadGoodsList()
}

// 分页切换
const handlePageChange = (page) => {
  currentPage.value = page
  loadGoodsList()
}

// 获取第一张图片
const getFirstImage = (pictureList) => {
  if (!pictureList) return '/default-image.jpg'
  const images = pictureList.split(',')
  return images[0] || '/default-image.jpg'
}

// 购买商品
const buyItem = async (item) => {
  try {
    const res = await api.createOrder({
      idleId: item.id,
      orderPrice: item.idlePrice
    })
    
    if (res.status_code === 1) {
      ElMessage.success('购买成功！')
    } else {
      ElMessage.error(res.msg || '购买失败')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('网络错误')
  }
}

// 显示完整描述
const showFullDesc = (item) => {
  currentDesc.value = item.idleDetails
  descDialogVisible.value = true
}
</script>

<style scoped>
.index-container {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.header {
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
}

.header-content {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header h1 {
  color: #8B5CF6;
  margin: 0;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.user-avatar {
  cursor: pointer;
  transition: transform 0.3s;
}

.user-avatar:hover {
  transform: scale(1.1);
}

.main-content {
  padding: 20px;
}

/* 分类标签样式 */
.category-tabs {
  margin-bottom: 24px;
  text-align: center;
}

/* 商品列表样式 */
.goods-list {
  min-height: 400px;
  margin-bottom: 20px;
}

.goods-card {
  margin-bottom: 20px;
  cursor: pointer;
  transition: transform 0.3s;
}

.goods-card:hover {
  transform: translateY(-5px);
}

.goods-image {
  width: 100%;
  height: 200px;
  overflow: hidden;
  border-radius: 4px;
  background-color: #f5f5f5;
}

.goods-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.goods-info {
  padding: 12px 0;
}

.goods-name {
  font-size: 16px;
  color: #303133;
  margin: 0 0 8px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.goods-price {
  font-size: 20px;
  color: #ff4d4f;
  font-weight: bold;
  margin: 0 0 8px 0;
}

.goods-desc-wrapper {
  position: relative;
  margin-bottom: 12px;
  min-height: 60px;
  display: flex;
  flex-direction: column;
}

.goods-desc {
  font-size: 13px;
  color: #606266;
  margin: 0;
  line-height: 1.5;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  height: 39px;
  flex-shrink: 0;
}

.goods-bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.goods-place {
  font-size: 14px;
  color: #909399;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>